import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time

# 校园网登录信息
USERNAME = "202111012027"  # 替换为你的校园网账号
PASSWORD = "moerp1cyp@qq.com"  # 替换为你的校园网密码
LOGIN_URL = "http://aaa.uestc.edu.cn"  # 校园网登录页面
CHECK_URL = "https://www.baidu.com"  # 用于检测网络状态的外部网站

# 检测网络状态
def check_network():
    try:
        response = requests.get(CHECK_URL, timeout=1)
        return response.status_code == 200
    except requests.RequestException:
        return False

# 自动登录校园网
def auto_login():
    try:
        driver = webdriver.Chrome()  # 使用Chrome浏览器，需提前安装ChromeDriver
        driver.get(LOGIN_URL)

        # 填写登录表单
        username_input = driver.find_element(By.ID, "username")
        password_input = driver.find_element(By.ID, "password")
        login_button = driver.find_element(By.ID, "school-login")

        username_input.send_keys(USERNAME)
        password_input.send_keys(PASSWORD)
        login_button.click()

        print("自动登录完成！")
        time.sleep(5)  # 等待登录完成
        driver.quit()
    except Exception as e:
        print(f"登录过程中出现错误：{e}")
        driver.quit()

# 主程序
def main():
    while True:
        print("检测网络状态...")
        if check_network():
            print("网络已连接，无需重新登录。")
        else:
            print("网络未连接，尝试自动登录...")
            auto_login()
        time.sleep(300)  # 每5分钟检测一次

if __name__ == "__main__":
    main()